package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.Result;
import com.itheima.reggie.pojo.OrderDetail;
import com.itheima.reggie.pojo.Orders;
import com.itheima.reggie.pojo.ShoppingCart;
import com.itheima.reggie.service.OrderDetailService;
import com.itheima.reggie.service.ShoppingCartService;
import com.itheima.reggie.service.impl.OrderServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.xml.crypto.Data;
import java.util.Date;

@RestController
@RequestMapping("/order")

public class OrderController {

    @Autowired
    private OrderServiceImpl orderService;

    @Autowired
    private ThreadLocal threadLocal;

    @Autowired
    private OrderDetailService orderDetailService;

    @PostMapping("/submit")
    public Result submit(@RequestBody Orders orders) {

        orderService.submit(orders);

        return Result.success("下单成功");
    }

    @GetMapping("/page")
    public Result getByPage(Integer page, Integer pageSize, String number,
                            @RequestParam(value = "beginTime",required = false)
                            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date begin,
                            @RequestParam(value = "endTime",required = false)
                            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date  end) {

        Page<Orders> ordersPage = new Page<>(page,pageSize);

        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();

        wrapper.eq(number!=null,Orders::getNumber,number);

        wrapper.gt(begin!=null,Orders::getCheckoutTime,begin).
                lt(end!=null,Orders::getCheckoutTime,end);

        orderService.page(ordersPage,wrapper);

        return Result.success(ordersPage);
    }

    @GetMapping("/userPage")
    public Result userPage(Integer page,Integer pageSize){

        Page<Orders> cartPage = new Page<>(page,pageSize);

        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();

        wrapper.eq(Orders::getUserId,threadLocal.get());

        wrapper.orderByDesc(Orders::getCheckoutTime);

        orderService.page(cartPage,wrapper);

        return Result.success(cartPage);

    }

    @PutMapping
    public Result update(@RequestBody Orders orders ){

/*        LambdaQueryWrapper<OrderDetail> wrapper = new LambdaQueryWrapper<>();

        wrapper.eq(OrderDetail::getId,orderDetail.getId());*/

        Orders one = orderService.getById(orders.getId());

        one.setStatus(orders.getStatus());

        orderService.updateById(one);

        return Result.success("修改成功");
    }

}
